require.config({baseUrl: '/js/lib', urlArgs: "v0.0.3"});
require(['zepto', 'lib', 'swiper'], function ($, lib, swiper) {
    lib = new lib();
    var fn = {
        pageNo: 1,
        noMore: false,
        orderType: 1,
        sId: lib.getUrlParam('sId') ? lib.getUrlParam('sId') : '4'
    };

    $.extend(fn, {
        init: function () {
            var _t = this;
            _t.bindEvent();
            _t.getShopBase();
            _t.getItems(_t.orderType);
            _t.roll();
            _t.getCartNum();
        },
        initBanner: function (data) {
            new swiper('.ui-banner', {
                autoplay: 5000, //可选选项，自动滑动
                pagination: '.swiper-pagination'
            });
        },
        bindEvent: function () {
            $(document).on("tap", "nav > i", function () {
                $(".ui-order-t").remove();
                if ($(this).text() === "编辑") {
                    $(this).text("完成");
                    $("body").append('<div class="ui-order-t ui-cart-op ui-input-foucs-hide"> <div> <i class="ui-no-choose" style="margin-top:0.5rem;float: left;"></i>全选 </div> <div class="ui-red-botton" style="width:4.4rem">删除</div> </div>');
                } else {
                    $(this).text("编辑");
                    $("body").append('<div class="ui-order-t ui-input-foucs-hide"> <div> <i class="ui-no-choose" style="margin-top:0.5rem;float: left;"></i>全选 </div> <div>总金额：<i>￥12556.00</i></div> <div class="ui-red-botton" style="width:4.4rem">去结算</div> </div>');
                }
                if ($(".ui-per-shop i.ui-choose").length === $(".ui-per-shop i.ui-cart-select").length) {
                    $(".ui-order-t i.ui-no-choose").attr("class", "ui-choose");
                }
            });
            //排序
            $('.ui-select-tj li').on('tap', function () {
                $('.ui-select-tj li').not($(this)).attr('class', '');
                if ($(this).hasClass('down')) {
                    fn.orderType = $(this).data('order');
                    $(this).attr('class', 'active');
                } else {
                    fn.orderType = $(this).data('order') + 1;
                    $(this).attr('class', 'active down');
                }
                $(".ui-per-shop").html('');
                fn.pageNo = 1;
                fn.noMore = false;
                fn.getItems(fn.orderType)
            });
            //购物车、去结算按钮
            $(document).on("tap", "#cart_icon", function () {
                if ($('.ui-cart-container').css('display') == 'none' && $('#iNums').text() != '0') {
                    lib.ajx(lib.getReq().ser + 'shoppingCart/cartList.action', {storageId: fn.sId}, function (data) {
                            if (data.infocode == '0') {
                                var html = '';
                                var info = data.info[0].goodsList;
                                for (var i in info) {
                                    html += `<li class="ui-gl-show">
                                              <ul>
                                                <li>${info[i].chName}</li>
                                                <li>￥${info[i].sellPrice}</li>
                                                <li class="ui-g-num" cartid="${info[i].shoppingCartId}">
                                                  <i class="ui-plus" style="display:block" miniCart="1"></i>
                                                  <input value="${info[i].goodsNum}" type="text" disabled="" style="display:block">
                                                  <i class="ui-add"></i>
                                                </li>
                                              </ul>
                                            </li>`;
                                }
                            }
                            $("#cart_list").html(html);
                        },
                        function () {
                            console.log('wine_shop.js => listStorageGoods.action fail!');
                        }
                    );
                } else if ($('.ui-cart-container').css('display') != 'none') {
                    $(".ui-per-shop").html('');
                    fn.getItems(fn.orderType);
                }
                if ($('#iNums').text() > 0) {
                    $('.ui-cart-container').toggle();
                }
            });
            $(document).on("tap", ".ui-red-botton", function () {
                location.href = '/cart.html';
            });
            //清空购物车
            $(document).on("tap", ".ui-s-name", function () {
                lib.ajx(lib.getReq().ser + 'shoppingCart/clearByStorageId.action', {storageId: fn.sId}, function (data) {
                        if (data.infocode == '0') {
                            if (confirm('确定清空购物车吗?')) location.reload();
                        }
                    },
                    function () {
                        console.log('wine_shop.js => clearByStorageId.action fail!');
                    }
                );
            });
            //加购物车
            $(document).on("tap", ".ui-add", function () {
                lib.onLoading();
                var _t = $(this);
                var num = parseInt(_t.prev().val());
                var gId = _t.parent().data('gid');
                if (num > 0) {
                    fn.updateCartNum(gId, _t.parent().attr('cartid'), num + 1, _t, function (leftNum) {
                        _t.prev().val((num + 1));
                        fn.getCartNum();
                    });
                } else {
                    var param = {
                        'goodsId': gId,
                        'storageId': fn.sId,
                        'goodsNum': 1
                    };
                    lib.ajx(lib.getReq().ser + 'shoppingCart/addToCart.action', param, function (data) {
                            if (data.infocode == '0') {
                                _t.prev().show().prev().show();
                                //TODO 返回shoppingCartId、购物车商品数、商品总件数和价格
                                _t.prev().val(num + 1);
                                _t.parent().attr('cartid', data.info);
                                fn.getCartNum();
                            }
                        },
                        function () {
                            console.log('wine_shop.js => addToCart.action fail!');
                        }
                    );
                }
            });
            //减购物车
            $(document).on("tap", ".ui-plus", function () {
                lib.onLoading();
                var _t = $(this);
                var num = parseInt($(this).next().val());
                var cartId = _t.parent().attr('cartid');
                if (num == 1) {
                    fn.clearCartNum(cartId, function () {
                        _t.next().val((num - 1));
                        _t.hide().next().hide();
                        if (_t.attr('miniCart') == '1') {
                            fn.getCartNum(function () {
                                if ($('#iNums').text() == '0') {
                                    $('.ui-cart-container').hide();
                                    $(".ui-per-shop").html('');
                                    fn.getItems(fn.orderType);
                                } else {
                                    _t.parent().parent().parent().remove();
                                }
                            });
                        } else {
                            fn.getCartNum();
                        }
                    });
                    return false;
                } else if (num === 0) {
                    return false;
                }

                var gId = _t.parent().data('gid');
                fn.updateCartNum(gId, cartId, num - 1, _t, function () {
                    _t.next().val((num - 1));
                    fn.getCartNum();
                });
            });
            //跳转详情页
            $(document).on('tap', '.ui-g-img', function () {
                location.href = '/detail.html?gId=' + $(this).data('goodsid') + '&sId=' + fn.sId;
            })
        },
        getShopBase: function () {
            var param = {'storageId': fn.sId};
            lib.ajx(lib.getReq().ser + 'storage/storageBaseInfo.action', param, function (data) {
                    if (data.infocode == '0') {
                        var info = data.info;
                        var sName = info.storageName;
                        $('span').html(sName);
                        $('.ui-s-name > div:eq(1)').html(sName);
                        var imgArr = ( info.imgUrl ).split(',');
                        var b = '<div class="swiper-wrapper">';
                        for (var i in imgArr) {
                            b += `<div class="swiper-slide">
                                        <a href="javacript:void('0')"><img class="lazy" src="${lib.getReq().imgPath + imgArr[i]}" /></a>
                                   </div>`
                        }
                        ;
                        b += '</div><div class="swiper-pagination"></div>';
                        $(".ui-banner").html(b);
                        fn.initBanner();
                    }
                },
                function () {
                    console.log('wine_shop.js => storageBaseInfo.action fail!');
                }
            );
        },
        getItems: function (order) {
            var items = '';
            lib.ajx(lib.getReq().ser + 'shoppingCart/cartList.action', {storageId: fn.sId}, function (data) {
                if (data.infocode === '0') {
                    //TODO 迷你购物车初始化数据
                    if (data.info.length > 0) items = data.info[0].goodsList;
                    lib.onLoading();
                    var param = {
                        'storageId': fn.sId,
                        'pageNo': fn.pageNo,
                        'pageSize': 20,
                        'orderBy': order
                    };
                    lib.ajx(lib.getReq().ser + 'storage/listStorageGoods.action', param, function (data) {
                            if (data.infocode == '0') {
                                var info = data.info;
                                if (info.goodsList.length < param.pageSize) fn.noMore = true;
                                var html = '';
                                for (var i in info.goodsList) {
                                    var cartId = '';
                                    var goodsNum = '';
                                    var status = 'none';
                                    for (var k in items) {
                                        if (info.goodsList[i].goodsId == items[k].goodsId) {
                                            cartId = items[k].shoppingCartId;
                                            goodsNum = items[k].goodsNum;
                                            status = 'block';
                                        }
                                    }
                                    html += `<ul class="ui-goods-info">
                                    <li>
                                      <div class="ui-g-img" data-goodsid="${info.goodsList[i].goodsId}"><img src="${lib.getReq().imgPath + info.goodsList[i].mainPicturePng}" /></div>
                                      <ul class="ui-g-desc">
                                        <li>${info.goodsList[i].chName}</li>
                                        <li>
                                          <i class="ui-g-price">￥${info.goodsList[i].sellPrice}</i>
                                          <i class="ui-g-warning">${info.goodsList[i].storeNum < 4 ? '库存仅剩' + info.goodsList[i].storeNum + '件' : ''}</i>
                                          <div class="ui-g-num" data-gid="${info.goodsList[i].goodsId}" cartid="${cartId}">
                                            <i class="ui-plus" style="display:${status}"></i>
                                            <input value="${goodsNum ? goodsNum : 0}" type="text" disabled style="display:${status}">
                                            <i class="ui-add"></i>
                                          </div>
                                        </li>
                                      </ul>
                                    </li>
                                   </ul>`;
                                }
                                $(".ui-per-shop").append(html);
                            }
                        },
                        function () {
                            console.log('wine_shop.js => listStorageGoods.action fail!');
                        }
                    );
                }
            }, function () {
                console.log('wine_shop.js => cartList.action fail!');
            });
        },
        updateCartNum: function (gId, cartId, gNum, _t, callback) {
            lib.onLoading();
            var param = {
                'goodsId': gId,
                'cartId': cartId,
                'goodsNum': gNum
            };
            lib.ajx(lib.getReq().ser + 'shoppingCart/updateGoodsNum.action', param, function (data) {
                    if (data.infocode == '0') {
                        var leftNum = data.info;
                        if (leftNum <= 3 && leftNum > 0) {
                            _t.parent().prev().html('库存仅剩' + leftNum + '件')
                        } else if (leftNum == 0) {
                            _t.parent().prev().html('该商品已售罄')
                        } else {
                            _t.parent().prev().html('')
                        }
                        if (typeof callback === 'function') callback.call();
                    } else if (data.infocode == '4') {
                        lib.showMessage('该商品已售罄，请稍后再试。');
                    }
                },
                function () {
                    console.log('wine_shop.js => updateGoodsNum.action fail!');
                }
            );
        },
        clearCartNum: function (cartId, callback) {
            lib.onLoading();
            var param = {
                'cartIds': [cartId]
            };
            lib.ajx(lib.getReq().ser + 'shoppingCart/clearByCartIds.action', param, function (data) {
                    if (data.infocode == '0') {
                        if (typeof callback === 'function') callback.call();
                    }
                },
                function () {
                    console.log('wine_shop.js => clearByCartIds.action fail!');
                }
            );
        },
        getCartNum: function (callback) {
            lib.ajx(lib.getReq().ser + 'shoppingCart/getCartNum.action', {}, function (data) {
                if (data.infocode === '0') {
                    $(".ui-bubble ,#iNums").text(data.info.cartNum);
                    $('#iTotal').text(data.info.amount);
                    if (typeof callback === 'function') callback.call();
                }
            }, function () {
                console.log('wine_shop.js => getCartNum.action fail!');
            });
        },
        roll: function () {
            lib.onLoading();
            var _t = this;
            $(window).scroll(function () {
                if (!_t.noMore && $(window).scrollTop() >= $(document).height() - $(window).height()) {
                    _t.pageNo++;
                    _t.getItems(_t.orderType);
                }
            });
        }
    });
    fn.init();
});